package awk.loader.class_loader.loader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class SimpleURLClassLoader extends URLClassLoader {//工程class类所在的路径

    public static String projectClassPath = "E:/IDE/work_place/ZJob-Note/bin/";//所有的测试的类都在同一个包下

    public SimpleURLClassLoader() {
        super(getMyURLs());
    }

    private static URL[] getMyURLs() {
        URL url = null;
        try {
            url = new File(projectClassPath).toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return new URL[]{url};
    }


    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

    /*** 重写loadClass，不采用双亲委托机制("java."开头的类还是会由系统默认ClassLoader加载)*/
    @Override
    public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class clazz = null;//查看HotSwapURLClassLoader实例缓存下，是否已经加载过class
        clazz = findLoadedClass(name);
        if (clazz != null) {
            if (resolve) {
                resolveClass(clazz);
            }
            return (clazz);
        }
        if (name.startsWith("java.")) {
            //如果类的包名为"java."开始，则有系统默认加载器AppClassLoader加载,//得到系统默认的加载cl，即AppClassLoader
            try {
                ClassLoader system = ClassLoader.getSystemClassLoader();
                clazz = system.loadClass(name);
                if (clazz != null) {
                    if (resolve) {
                        resolveClass(clazz);
                    }
                    return (clazz);
                }
            } catch (ClassNotFoundException e) {//Ignore
            }
        }
        return this.findClass(name);
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }

}
